//
//  WebViewApp.swift
//  kz
//
//  Created by Wai Yin Chan on 15/9/2017.
//  Copyright © 2017 Tech_001. All rights reserved.
//

import Foundation
import UIKit

protocol WebViewAppProtocol {
    var name: String { get }
    var identityHostName: String { get }
    var appUrl: URL? { get set }
    var requestUrl: URL? { get set }
    var downloadUrlString: String { get }
    
    func updateAppUrl()
}

class WebViewApp {
    public static func getInstance(_ url: URL) -> WebViewAppProtocol? {
        let apps : [WebViewAppProtocol] = [
            AliPayApp()
        ]
        
        for var app in apps {
            if url.absoluteString.contains("://\(app.identityHostName)/") {
                app.requestUrl = url
                app.updateAppUrl()
                return app
            }
        }
        return nil
    }

    public static func route(_ app: WebViewAppProtocol) {
        if let url = app.appUrl {
            if UIApplication.shared.canOpenURL(url){
                    ToolHelper.statisticsPage(pageName:"首页-万博体育-APP唤醒")
                UIApplication.shared.openURL(url)
            }else{
                let dialogMessage = UIAlertController(title: app.name, message: "是否下载\(app.name)", preferredStyle: .alert)
                dialogMessage.view.tintColor = UIColor.black
                
                let ok = UIAlertAction(title: "前往下载", style: .default, handler: { (action) -> Void in
                      ToolHelper.statisticsPage(pageName:"首页-万博体育-APP下载页")
                    if let url = URL(string: app.downloadUrlString) {
                        UIApplication.shared.openURL(url)
                    }
                })
                
                let cancel = UIAlertAction(title: "取消", style: .default, handler: { (action) -> Void in
                    
                })
                
                dialogMessage.addAction(ok)
                dialogMessage.addAction(cancel)
                UIHelper.getTopController()!.present(dialogMessage, animated: true, completion: nil)
            }
        }
    }
}
